#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

#include "./../../inc/homepage.h"
#include "./../../inc/msg_popup.h"
#include "./../../inc/cJSON.h"
#include "./../../inc/user_event.h"
#include "./../../inc/tcp.h"

#define ULGRAY 0xF5F5F5
#define LDWHITE 0xF6F6F6

static void close_user_card_event(lv_event_t * e);
static void add_friend_event(lv_event_t * e);
static void user_card_delete_event_cb(lv_event_t * e);

void show_user_card(lv_obj_t * parent, const char * name)
{
    // 入参校验
    if(name == NULL || strlen(name) == 0) {
        printf("show_user_card: 无效的用户名\n");
        return;
    }

    // 为用户名分配堆内存
    char * name_copy = (char *)malloc(strlen(name) + 1);
    if(name_copy == NULL) {
        printf("show_user_card: 内存分配失败\n");
        return;
    }
    strcpy(name_copy, name);

    // 创建半透明背景层
    lv_obj_t * overlay = lv_obj_create(parent);
    lv_obj_set_size(overlay, LV_HOR_RES, LV_VER_RES);
    lv_obj_set_style_bg_color(overlay, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(overlay, LV_OPA_50, 0);
    lv_obj_set_style_border_width(overlay, 0, 0);
    lv_obj_set_style_radius(overlay, 0, 0);
    lv_obj_center(overlay);
    lv_obj_clear_flag(overlay, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    // 存储用户名拷贝到背景层用户数据（用于释放）
    lv_obj_set_user_data(overlay, name_copy);
    lv_obj_add_event_cb(overlay, user_card_delete_event_cb, LV_EVENT_DELETE, NULL);

    lv_obj_t * user_card = lv_obj_create(overlay);
    lv_obj_set_size(user_card, 300, 200);
    lv_obj_set_style_radius(user_card, 20, 0);
    lv_obj_set_pos(user_card, 0, 0);
    lv_obj_set_style_bg_color(user_card, lv_color_hex(WHITE), 0);
    lv_obj_set_style_bg_opa(user_card, LV_OPA_100, 0);
    lv_obj_set_style_border_width(user_card, 0, 0);
    lv_obj_set_style_border_color(user_card, lv_color_hex(0xE0E0E0), 0);
    lv_obj_set_style_shadow_width(user_card, 20, 0);
    lv_obj_set_style_shadow_opa(user_card, LV_OPA_30, 0);
    lv_obj_clear_flag(user_card, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_center(user_card);

    lv_obj_t * user_box = lv_obj_create(user_card);
    lv_obj_set_size(user_box, LV_PCT(100), LV_PCT(70));
    lv_obj_set_style_radius(user_box, 0, 0);
    lv_obj_set_style_bg_color(user_box, lv_color_hex(WHITE), 0);
    lv_obj_set_style_bg_opa(user_box, LV_OPA_100, 0);
    lv_obj_set_style_border_width(user_box, 0, 0);
    lv_obj_clear_flag(user_box, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    lv_obj_t * avatar = lv_img_create(user_box);
    lv_img_set_src(avatar, "S:res/ui/user_s.png");
    lv_obj_set_size(avatar, 48, 48);
    lv_obj_align(avatar, LV_ALIGN_LEFT_MID, 10, 0);

    lv_obj_t * username_label = lv_label_create(user_box);
    lv_label_set_text(username_label, name);
    lv_obj_set_style_text_color(username_label, lv_color_hex(0x000000), 0);
    lv_obj_set_style_text_font(username_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_size(username_label, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
    lv_obj_align_to(username_label, avatar, LV_ALIGN_OUT_RIGHT_MID, 10, 0);
    lv_obj_set_style_text_align(username_label, LV_TEXT_ALIGN_CENTER, 0);

    // 下划线
    lv_obj_t * title_underline = lv_obj_create(user_box);
    lv_obj_set_pos(title_underline, 0, LV_PCT(99));
    lv_obj_set_size(title_underline, LV_PCT(100), 1);
    lv_obj_set_style_bg_color(title_underline, lv_color_hex(ULGRAY), 0);
    lv_obj_set_style_radius(title_underline, 0, 0);
    lv_obj_set_style_border_width(title_underline, 0, 0);

    lv_obj_t * bottom_btn = lv_btn_create(user_card);
    lv_obj_set_size(bottom_btn, 120, 40);
    lv_obj_set_style_bg_color(bottom_btn, lv_color_hex(0xF0F0F0), 0);
    lv_obj_set_style_bg_opa(bottom_btn, LV_OPA_100, 0);
    lv_obj_set_style_radius(bottom_btn, 8, 0); // 8px圆角，更美观
    lv_obj_set_style_border_width(bottom_btn, 0, 0);
    lv_obj_align(bottom_btn, LV_ALIGN_BOTTOM_MID, 0, 5);

    lv_obj_t * btn_label = lv_label_create(bottom_btn);
    lv_label_set_text(btn_label, "添加好友");
    lv_obj_set_style_text_color(btn_label, lv_color_hex(0x333333), 0);
    lv_obj_set_style_text_font(btn_label, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_center(btn_label);

    // 绑定堆内存拷贝而非原指针
    lv_obj_add_event_cb(bottom_btn, add_friend_event, LV_EVENT_CLICKED, name_copy);
    lv_obj_add_event_cb(overlay, close_user_card_event, LV_EVENT_CLICKED, NULL);

    lv_obj_add_flag(user_card, LV_OBJ_FLAG_CLICKABLE);
    lv_obj_add_event_cb(user_card, NULL, LV_EVENT_CLICKED, NULL); // 空回调阻止冒泡
}

static void close_user_card_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("close user card\n");

        // 获取事件源对象和当前目标对象
        lv_obj_t * target         = lv_event_get_target(e);
        lv_obj_t * current_target = lv_event_get_current_target(e);

        // 只有点击的是overlay本身（半透明背景）才关闭卡片
        if(target == current_target) {
            // 先移除事件回调，避免删除时再次触发
            lv_obj_remove_event_cb(current_target, close_user_card_event);
            lv_obj_del(current_target);
            printf("close user card over\n");
        }
    }
}

static void add_friend_event(lv_event_t * e)
{
    char * apply_to = lv_event_get_user_data(e);

    if(apply_to == NULL || strlen(apply_to) == 0) {
        printf("add_friend_event: 被申请人信息无效\n");
        return;
    }
    if(user_event.userid == NULL || strlen(user_event.userid) == 0) {
        printf("add_friend_event: 申请人信息未初始化\n");
        return;
    }

    // 创建根JSON对象
    cJSON * root = cJSON_CreateObject();
    if(root == NULL) {
        printf("创建JSON根对象失败\n");
        return;
    }

    //  添加type字段
    cJSON_AddStringToObject(root, "type", "add_friend");

    // 创建payload对象并添加字段
    cJSON * payload = cJSON_CreateObject();
    if(payload == NULL) {
        printf("创建payload对象失败\n");
        cJSON_Delete(root);
        return;
    }

    // 添加申请人和被申请人
    cJSON_AddStringToObject(payload, "apply_from", user_event.userid); // 申请人userid
    cJSON_AddStringToObject(payload, "apply_to", apply_to);            // 被申请人userid

    // cJSON_AddStringToObject(payload, "apply_msg", "请加我为好友"); // 添加申请留言

    cJSON_AddItemToObject(root, "payload", payload);

    char * json_str = cJSON_PrintUnformatted(root);
    if(json_str == NULL) {
        printf("JSON转换为字符串失败\n");
        cJSON_Delete(root);
        return;
    }

    // printf("打包的添加好友JSON: %s\n", json_str);

    send_message_to_server(&server_info, json_str);

    free(json_str);
    cJSON_Delete(root);
}

// 卡片删除时释放用户名内存
static void user_card_delete_event_cb(lv_event_t * e)
{
    lv_obj_t * overlay = lv_event_get_target(e);
    if(overlay == NULL) return;

    char * name_copy = (char *)lv_obj_get_user_data(overlay);
    if(name_copy != NULL) {
        free(name_copy);
        lv_obj_set_user_data(overlay, NULL);
    }
}